<template>
  <div class="app-container">
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordForm">取消</el-button>
          <el-button type="primary" @click="submitPassword" :loading="passwordLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 侧边栏 -->
    <div class="sidebar" :class="{ 'collapsed': isCollapsed }">
      <div class="sidebar-header">
        <div class="logo">Agent管理平台</div>
        <el-icon class="collapse-icon" @click="toggleCollapse">
          <component :is="isCollapsed ? 'Expand' : 'Fold'" />
        </el-icon>
      </div>
      
      <el-menu
        :default-active="activeRoute"
        class="sidebar-menu"
        :collapse="isCollapsed"
        router
      >
        <el-menu-item index="/">
          <el-icon><DataLine /></el-icon>
          <template #title>仪表盘</template>
        </el-menu-item>
        
        <!-- 添加智能体管理菜单项 -->
        <el-menu-item index="/agents">
          <el-icon><HelpFilled /></el-icon>
          <template #title>智能体管理</template>
        </el-menu-item>
        
        <el-sub-menu index="user-management">
          <template #title>
            <el-icon><Setting /></el-icon>
            <span>系统设置</span>
          </template>
          <el-menu-item index="/departments">
            <el-icon><OfficeBuilding /></el-icon>
            <span>部门管理</span>
          </el-menu-item>
          <el-menu-item index="/users">
            <el-icon><UserFilled /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="/roles">
            <el-icon><Lock /></el-icon>
            <span>角色管理</span>
          </el-menu-item>
        </el-sub-menu>
        
        <el-sub-menu index="log-management">
          <template #title>
            <el-icon><Timer /></el-icon>
            <span>日志管理</span>
          </template>
          <el-menu-item index="/request-logs">
            <el-icon><Document /></el-icon>
            <span>请求日志</span>
          </el-menu-item>
          <el-menu-item index="/login-history">
            <el-icon><Key /></el-icon>
            <span>登录历史</span>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </div>
    
    <div class="main-wrapper">
      <!-- 顶部导航栏 -->
      <el-header class="navbar">
        <!-- 面包屑导航 -->
        <div class="breadcrumb-container">
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item v-for="(item, index) in breadcrumbItems" :key="index">
              {{ item.title }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <div class="user-area">
          <!-- WebSocket状态指示器 -->
          <div class="ws-indicator">
            <span class="ws-status" :class="wsStatusClass"></span>
            <span class="ws-text">{{ wsStatusText }}</span>
          </div>
          
          <el-dropdown @command="handleCommand">
            <div class="user-profile">
              <el-avatar :size="32" :src="avatarUrl">{{ usernameInitial }}</el-avatar>
              <span class="username">{{ username }}</span>
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><UserFilled /></el-icon>
                  个人信息
                </el-dropdown-item>
                <el-dropdown-item command="changePassword">
                  <el-icon><Lock /></el-icon>
                  修改密码
                </el-dropdown-item>
                <el-dropdown-item command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      
      <!-- 标签页导航 -->
      <TabsView />
      
      <!-- 主内容区域 -->
      <div class="main-content">
        <!-- 使用keep-alive和transition组件优化页面切换 -->
        <transition name="fade" mode="out-in">
          <keep-alive>
            <router-view v-if="!tabsStore.refreshingTab" />
          </keep-alive>
        </transition>
      </div>
      
      <!-- 页脚 -->
      <footer class="app-footer">
        <div class="footer-content">
          <div class="footer-info">
            <p> © 2025 HEC 版权所有</p>
          </div>
        </div>
      </footer>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref, watch, reactive, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useTabsStore } from '@/stores/tabs'
import { initWebSocket, wsStatus, wsConnected, enableAutoReconnect } from '@/api/websocket'
import TabsView from '@/components/TabsView.vue'
import { ElMessage } from 'element-plus'
import { formatAvatarUrl } from '@/utils/format'
import { changeUserPassword } from '@/api/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const tabsStore = useTabsStore()
const passwordFormRef = ref(null)
const showPasswordDialog = ref(false)
const passwordLoading = ref(false)

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 提交密码修改
const submitPassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true
      try {
        const passwordData = {
          old_password: passwordForm.oldPassword,
          new_password: passwordForm.newPassword
        }
        
        // 调用API修改密码
        await changeUserPassword(passwordData)
        ElMessage({
          type: 'success',
          message: '密码修改成功，请重新登录'
        })
        resetPasswordForm()
        // 修改成功后退出登录
        userStore.logout()
        router.push('/login')
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改密码失败')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 重置密码表单
const resetPasswordForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
  showPasswordDialog.value = false
}

// 获取当前年份
const currentYear = new Date().getFullYear()

// 侧边栏折叠状态
const isCollapsed = ref(false)

// 切换侧边栏折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

// 用户信息
const username = computed(() => userStore.username || '用户')
const usernameInitial = computed(() => {
  const name = userStore.username || '用户'
  return name.charAt(0).toUpperCase()
})
// 获取头像URL（支持base64）
const avatarUrl = computed(() => {
  return formatAvatarUrl(userStore.getAvatar)
})

// 面包屑导航
const breadcrumbItems = computed(() => {
  const items = []

  if (route.meta && route.meta.title) {
    // 检查是否有父级菜单
    if (route.path.includes('/users') || route.path.includes('/roles') || route.path.includes('/departments')) {
      items.push({ title: '系统设置' })
    } else if (route.path.includes('/request-logs') || route.path.includes('/login-history')) {
      items.push({ title: '日志管理' })
    } else if (route.path.includes('/agents')) {
      items.push({ title: '智能体管理' })
    }

    items.push({ title: route.meta.title })
  }

  return items
})

// WebSocket状态
const wsStatusClass = computed(() => {
  switch (wsStatus.value) {
    case 'connected': return 'connected'
    case 'disconnected': return 'disconnected'
    case 'connecting': return 'connecting'
    default: return 'disconnected'
  }
})

const wsStatusText = computed(() => {
  switch (wsStatus.value) {
    case 'connected': return '实时数据已连接'
    case 'disconnected': return '实时数据已断开'
    case 'connecting': return '连接中...'
    default: return '连接错误'
  }
})

// 当前活动路由
const activeRoute = computed(() => route.path)

// 处理下拉菜单命令
const handleCommand = (command) => {
  if (command === 'logout') {
    userStore.logout()
    router.push('/login')
  } else if (command === 'profile') {
    // 跳转到个人信息页面
    router.push('/profile')
  } else if (command === 'changePassword') {
    // 显示修改密码对话框
    showPasswordDialog.value = true
  }
}

// 监听路由变化，更新标签页
watch(
  () => route,
  (newRoute) => {
    if (newRoute.path.includes('/redirect')) return
    
    // 只有在布局视图下的路由才添加到标签页
    if (newRoute.matched.length > 0 && newRoute.matched[0].name === 'Layout') {
      // 使用nextTick确保DOM更新后再添加标签，避免抖动
      nextTick(() => {
        tabsStore.addTab(newRoute)
      })
    }
  },
  { immediate: true, deep: true }
)

onMounted(() => {
  // 初始化WebSocket
  initWebSocket()
  
  // 启用WebSocket自动重连
  enableAutoReconnect()
})
</script>

<style lang="scss" scoped>
.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.app-container {
  display: flex;
  height: 100%;
}

.sidebar {
  width: 240px;
  height: 100%;
  background-color: #304156;
  transition: width 0.3s;
  overflow: hidden;
  
  &.collapsed {
    width: 64px;
  }
  
  .sidebar-header {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 16px;
    color: #fff;
    
    .logo {
      font-size: 18px;
      font-weight: 600;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .collapse-icon {
      cursor: pointer;
      font-size: 20px;
      
      &:hover {
        color: var(--el-color-primary);
      }
    }
  }
  
  .sidebar-menu {
    border-right: none;
    background-color: transparent;
    
    :deep(.el-menu-item),
    :deep(.el-sub-menu__title) {
      color: #bfcbd9;
      
      &:hover {
        color: #fff;
        background-color: #263445;
      }
      
      &.is-active {
        color: #fff;
        background-color: rgba(64, 158, 255, 0.7);
      }
    }
    
    :deep(.el-menu-item.is-active) {
      color: #fff;
      background-color: rgba(64, 158, 255, 0.7);
    }
    
    // 二级菜单背景色
    :deep(.el-menu--inline) {
      background-color: #1f2d3d;
    }
  }
}

.main-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  
  .main-content {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background-color: #f5f7fa;
    position: relative;
  }
}

.navbar {
  height: 60px;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .breadcrumb-container {
    display: flex;
    align-items: center;
  }
  
  .user-area {
    display: flex;
    align-items: center;
    
    .ws-indicator {
      margin-right: 20px;
      display: flex;
      align-items: center;
      
      .ws-status {
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin-right: 6px;
        
        &.connected {
          background-color: var(--el-color-success);
        }
        
        &.disconnected {
          background-color: var(--el-color-danger);
        }
        
        &.connecting {
          background-color: var(--el-color-warning);
          animation: blink 1s infinite;
        }
      }
      
      .ws-text {
        font-size: 12px;
        color: #909399;
      }
    }
    
    .user-profile {
      display: flex;
      align-items: center;
      cursor: pointer;
      
      .username {
        margin: 0 8px;
        color: #303133;
      }
    }
  }
}

.app-footer {
  height: 40px;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
  padding: 0 20px;
  
  .footer-content {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .footer-info {
      text-align: center;
      
      p {
        margin: 0;
        padding: 0;
        font-size: 12px;
        color: #909399;
        line-height: 1.5;
      }
    }
  }
}

/* 添加页面过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

@keyframes blink {
  0% { opacity: 0.3; }
  50% { opacity: 1; }
  100% { opacity: 0.3; }
}
</style>